package cn.myweb.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import java.io.*;

public class FileDownloadAction extends ActionSupport {

    private String inputPath;
    private String fileName;
    private InputStream inputStream;
    private String contentType;

    private String msg;

    @Action(value = "download"
            //,params = {"inputPath","/upload"}
            ,results = {
            @Result(name = "input",location = "download.jsp")
            ,@Result(name = "success",type="stream",params = {
                    "contentType","application/octet-stream"
                    ,"inputName","inputStream"
                    ,"contentDisposition","attachment;filename='%{fileName}'"
            })
    })
    public String download() throws UnsupportedEncodingException {
        this.setMsg("attachment;filename="
                + java.net.URLEncoder.encode(fileName, "UTF-8"));
        System.out.println("---------------download");
        return "success";
    }

    public String getInputPath() {
        return inputPath;
    }

    public void setInputPath(String inputPath) {
        this.inputPath = inputPath;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public InputStream getInputStream() throws FileNotFoundException {
       // String path = ServletActionContext.getServletContext().getRealPath(inputPath);

        String myFileFileName=this.getFileName();//"198.jpg";
        String real_path = ServletActionContext.getServletContext().getRealPath(File.separator);

        real_path =real_path.substring(0,real_path.lastIndexOf("\\"))+File.separator+"upload";
        String path2 = real_path+ File.separator+myFileFileName;
        System.out.println("path2: "+ path2);

        return new BufferedInputStream(new FileInputStream(path2));
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}
